package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/12 17:24
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
 */
public class Title121 {

    /**
     * 只能某一天买入
     * @param prices
     * @return
     */
    public int maxProfit(int[] prices) {
        int min = prices[0];
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if(prices[i] < min){
                //记录最低价格
                min = prices[i];
            }else if(prices[i] - min > profit){
                profit = prices[i] - min;
            }
        }
        return profit;
    }

    /**
     * dp[i][0]：第i天持有股票所得的现金 (买）
     * dp[i][1]：第i天不持有股票所得的现金 （卖）
     * 递推公式：
     * dp[i][0]：dp[i][0] = max(dp[i-1][0], -prices[i])
     * dp[i][1]：dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i])
     *
     * @param prices
     * @return
     */
    public int maxProfit1(int[] prices) {
        int[][] dp = new int[prices.length][2];
        //初始化
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for (int i = 1; i < prices.length; i++) {
            //当天不买、买
            dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
            //当天不卖、卖
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }
        return dp[prices.length - 1][1];
    }

    public int maxProfit2(int[] prices) {
        int[][] dp = new int[2][2];
        //初始化
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for (int i = 1; i < prices.length; i++) {
            //当天不买、买
            dp[i%2][0] = Math.max(dp[(i - 1)%2][0], -prices[i]);
            //当天不卖、卖
            dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]);
        }
        return dp[(prices.length - 1) % 2][1];
    }


    /**
     * 状态：不操作、买、卖
     * dp[i][j]：表示第i天时保持状态j时有多少钱
     * 递推公式：dp[i][1] = Math.max(dp[i-1][0] - prices. dp[i-1][1])
     *           dp[i][2] = Math.max(dp[i-1][1] + prices, dp[i-1][2])
     * @param prices
     * @return
     */
    public int maxProfit3(int[] prices) {
        int[][] dp = new int[2][3];
        //初始化
        dp[0][1] = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            //当天不买、买
            dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], -prices[i]);
            //当天不卖、卖
            dp[i % 2][2] = Math.max(dp[(i - 1) % 2][2], dp[(i - 1) % 2][1] + prices[i]);
        }
        return dp[(prices.length - 1) % 2][2];
    }

    public static void main(String[] args) {

    }
}
